import { Injectable } from '@nestjs/common';
import { generateRandomStr } from './utils/generateRandomStr';
import { Cron, CronExpression } from '@nestjs/schedule';
import { EntityManager } from 'typeorm';
import { UniqueCode } from './entity/uniqueCode';

@Injectable()
export class UniqueCodeService {
  constructor(private readonly entityManager: EntityManager) {}

  async generateCode() {
    const code = generateRandomStr(6);

    const res_code = await this.entityManager.findOne(UniqueCode, {
      where: { code: code },
    });

    if (!res_code) {
      return await this.entityManager.save(UniqueCode, {
        code: code,
        status: 0,
      });
    } else {
      return await this.generateCode();
    }
  }

  // 每天的凌晨四点创建100·00个code
  @Cron(CronExpression.EVERY_DAY_AT_4AM)
  async batchGenerateCode() {
    for (let i = 0; i < 10000; i++) {
      await this.generateCode();
    }
  }
}
